package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutContract;
import com.lkd.contract.VendoutData;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;

import static com.lkd.common.VMSystem.ORDER_STATUS_VENDOUT_FAIL;
import static com.lkd.common.VMSystem.ORDER_STATUS_VENDOUT_SUCCESS;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-07-22 16:16
 */
@Component
@Topic(TopicConfig.VMS_RESULT_TOPIC)
@Slf4j
public class VendoutCompleteHandler implements MsgHandler {

    @Autowired
    private ChannelService channelService;
    @Autowired
    private VendoutRunningService vendoutRunningService;

    @Override
    @Transactional
    public void process(String jsonMsg) throws IOException {
        //1.反序列化
        VendoutResultContract contract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        VendoutData vendoutData = contract.getVendoutData();
        if (vendoutData == null || StringUtils.isEmpty(vendoutData.getOrderNo())
                || StringUtils.isEmpty(vendoutData.getChannelCode()) || vendoutData.getSkuId() == 0) {
            log.error("出货结果消息处理报错,消息内容:" + jsonMsg);
            return;
        }

        //2.更新数据库状态
        if (contract.isSuccess()) {
            //成功,记录进行更新
            vendoutRunningService.update(Wrappers.<VendoutRunningEntity>lambdaUpdate()
                    .eq(VendoutRunningEntity::getOrderNo, vendoutData.getOrderNo())
                    .eq(VendoutRunningEntity::getSkuId, vendoutData.getSkuId())
                    .set(VendoutRunningEntity::getStatus, true));
        } else {
            //失败回滚库存
            channelService.update(Wrappers.<ChannelEntity>lambdaUpdate()
                    .eq(ChannelEntity::getChannelCode, vendoutData.getChannelCode())
                    .eq(ChannelEntity::getInnerCode, contract.getInnerCode())
                    .setSql("current_capacity = current_capacity + 1"));
        }

    }
}
